package com.solution.admin.point.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.solution.admin.point.entity.SignPointSettingsEntity;
import com.solution.admin.point.service.SignPointSettingsService;
import com.solution.common.constants.PublicStatus.SysCode;
import com.solution.common.controller.BaseController;
import com.solution.common.entity.BaseReturn;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.DateUtils;
import com.solution.common.utils.string.StringUtil;

/**
 * 签到积分设置信息web控制层
 * 
 * @author xu_cc
 * @date 2017-10-20 14:18:43
 */
@RequestMapping("/signPointSettings")
@Controller
public class SignPointSettingsController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(SignPointSettingsController.class);

	@Autowired
	private SignPointSettingsService signPointSettingsService;

	/**
	 * 跳转签到积分设置信息查询页面
	 * 
	 * @param SignPointSettings
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-10-20 14:18:43
	 */
	@RequestMapping("/toListSignPointSettingsPage")
	public String toListSignPointSettingsPage(SignPointSettingsEntity signPointSettings, HttpServletRequest request, Model model) {
		try {
			String dateStr = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
			dateStr += " 00:00:00";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			model.addAttribute("systemTime", sdf.parse(dateStr).getTime());
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("systemTime", System.currentTimeMillis());
		}
		return "point/signPointSettings_list";
	}

	/**
	 * 分页查询签到积分设置信息列表
	 * 
	 * @param signPointSettings
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-10-20 14:18:43
	 */
	@RequestMapping("/listSignPointSettingsPage")
	@ResponseBody
	public JSONGrid listSignPointSettingsPage(SignPointSettingsEntity signPointSettings, HttpServletRequest request) {
		int pageNum = Integer.parseInt(request.getParameter("page").toString());
		int numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);

		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			PageBean pageBean = signPointSettingsService.listSignPointSettingsPage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(), pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询签到积分设置信息失败", logger, e);
		}
		return new JSONGrid();
	}

	/**
	 * 跳转新增页面
	 * 
	 * @return string 跳转页面路径
	 * @author xu_cc
	 * @date 2017-10-20 14:18:43
	 */
	@RequestMapping("/toAddSignPointSettings")
	public String toAddSignPointSettings(HttpServletRequest request) {
		request.setAttribute("opFlag", "add");
		return "point/signPointSettings_form";
	}

	/**
	 * 跳转编辑页面
	 * 
	 * @return string 跳转页面路径
	 * @author xu_cc
	 * @date 2017-10-20 14:18:43
	 */
	@RequestMapping("/toUpdateSignPointSettings")
	public String toUpdateSignPointSettings(HttpServletRequest request) {
		// 编辑操作
		request.setAttribute("opFlag", "edit");
		long id = Long.valueOf(request.getParameter("id"));
		try {
			SignPointSettingsEntity signPointSettings = signPointSettingsService.getSignPointSettingsById(id);
			String pattern = "yyyy-MM-dd";
			String startTimeStr = DateFormatUtils.format(signPointSettings.getStartTime(), pattern);
			String endTimeStr = DateFormatUtils.format(signPointSettings.getEndTime(), pattern);
			signPointSettings.setStartTimeStr(startTimeStr);
			signPointSettings.setEndTimeStr(endTimeStr);
			request.setAttribute("signPointSettings", signPointSettings);
		} catch (Exception e) {
			handleException("跳转编辑签到积分设置信息页面错误", logger, e);
		}
		return "point/signPointSettings_form";
	}

	/**
	 * 新增或保存签到积分设置信息
	 * 
	 * @param request
	 *            请求对象
	 * @param signPointSettingsEntity
	 *            签到积分设置信息实体
	 * @return
	 * @author xu_cc
	 * @date 2017-10-20 14:18:43
	 */
	@RequestMapping("/saveSignPointSettings")
	@ResponseBody
	public BaseReturn saveSignPointSettings(HttpServletRequest request, SignPointSettingsEntity signPointSettingsEntity, String signDate) {
		BaseReturn result = new BaseReturn();
		try {
			// 活动日期
			String[] signDateArr = signDate.split(" - ");
			Date startDate = DateUtils.parseDate(signDateArr[0]);
			Date endDate = DateUtils.parseDate(signDateArr[1]);
			Long id = signPointSettingsEntity.getId();
			// Date startTime =
			// com.solution.common.utils.DateUtils.parseDate(signPointSettingsEntity.getStartTimeStr());
			// Date endTime =
			// com.solution.common.utils.DateUtils.parseDate(signPointSettingsEntity.getEndTimeStr());
			signPointSettingsEntity.setStartTime(startDate);
			signPointSettingsEntity.setEndTime(endDate);
			signPointSettingsEntity.setCreater(getUserName());
			signPointSettingsEntity.setModifier(getUserName());

			String pattern = "yyyy-MM-dd";
			// 校验时间是否冲突（同一时间段只能有一条设置是有效的）
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("startTime", signDateArr[0]);
			param.put("endTime", signDateArr[1]);
			// 查看是否有时间冲突的记录
			List<SignPointSettingsEntity> edList = signPointSettingsService.listSignPointSettings(param);
			if (null == id) {
				// 新增的情况下
				if (null != edList && edList.size() > 0) {
					String startTimeStr = DateFormatUtils.format(edList.get(0).getStartTime(), pattern);
					String endTimeStr = DateFormatUtils.format(edList.get(0).getEndTime(), pattern);
					result.setCode(SysCode.FAILED);
					result.setMsg(StringUtil.formatString("保存失败，签到规则在当前时间段内有冲突！已存在规则起止日期：%s ~ %s", startTimeStr, endTimeStr));
					return result;
				}
				signPointSettingsService.saveSignPointSettings(signPointSettingsEntity);
			} else {
				if (null != edList && edList.size() > 0) {
					for (SignPointSettingsEntity oldSignSetting : edList) {
						if (!oldSignSetting.getId().equals(id)) {
							// 不是自己
							String startTimeStr = DateFormatUtils.format(oldSignSetting.getStartTime(), pattern);
							String endTimeStr = DateFormatUtils.format(oldSignSetting.getEndTime(), pattern);
							result.setCode(SysCode.FAILED);
							result.setMsg(StringUtil.formatString("保存失败，签到规则在当前时间段内有冲突！已存在规则起止日期：%s ~ %s", startTimeStr, endTimeStr));
							return result;
						}
					}
				}
				signPointSettingsService.updateSignPointSettings(signPointSettingsEntity);
			}
			result.setCode(SysCode.SUCCESS);
			result.setMsg("签到积分设置信息保存成功！");
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("签到积分设置信息保存异常！");
		}
		return result;
	}

}
